

<template>
  <div>
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card" style="margin-bottom: 24px;">
      <div style="display: flex; align-items: center; padding: 20px;">
        <el-avatar :size="64" style="background-color: #409eff; margin-right: 16px;">
          <i class="el-icon-user-solid" style="font-size: 32px;"></i>
        </el-avatar>
        <div>
          <div style="font-size: 20px; font-weight: bold; margin-bottom: 8px; color: #303133;">欢迎回来，专家</div>
          <div style="font-size: 14px; color: #909399;">今天是 {{ currentDate }}，祝您工作愉快！</div>
        </div>
      </div>
    </el-card>
    
    <!-- 专家默认进入需要填写询标信息，填写后展示询标信息 -->
    <el-card class="form-card" style="margin-bottom: 16px;">
      <div slot="header" style="display: flex; align-items: center; justify-content: space-between;">
        <div style="display: flex; align-items: center;">
          <i class="el-icon-edit" style="color: #409eff; margin-right: 8px; font-size: 18px;"></i>
          <span style="font-size: 18px; font-weight: bold;">项目询标</span>
        </div>
        <el-button
          type="text"
          style="color: #409eff;"
          @click="goToExpertHome"
        >
          查看询标结果
          <i class="el-icon-arrow-right" style="margin-left: 4px;"></i>
        </el-button>
      </div>
      
      <el-form ref="form" :model="formData" label-width="120px">
        <el-row :gutter="16">
          <el-col :xs="24" :md="8" v-for="(bidder, index) in bidders" :key="index">
            <el-card class="bidder-card" style="margin-bottom: 12px;" shadow="hover">
              <div style="padding: 16px;">
                <div style="display: flex; align-items: center; margin-bottom: 8px;">
                  <i class="el-icon-office-building" style="color: #409eff; margin-right: 8px;"></i>
                  <span style="font-weight: 500;">{{ bidder.name }}</span>
                </div>
                <div style="display: flex; align-items: center; font-size: 14px; color: #606266;">
                  <i class="el-icon-user" style="color: #409eff; margin-right: 8px;"></i>
                  <span>{{ bidder.contactName }}</span>
                  <span style="margin: 0 8px; color: #c0c4cc;">/</span>
                  <span>{{ bidder.contactPhone }}</span>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="24">
            <el-form-item label="项目标号">
              <el-input
                v-model="ProjectNo"
                placeholder="项目标号"
                readonly
                disabled
              ></el-input>
            </el-form-item>
            
            <el-form-item label="询标截止时间" prop="DeadlineTime">
              <el-date-picker
                v-model="formData.DeadlineTime"
                type="datetime"
                placeholder="选择询标截止时间"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
            
            <el-form-item label="附件列表">
              <template v-if="formData.IsSend">
                <!-- 已发送状态的附件列表 -->
                <div v-if="responsesAttachement.attachments?.length > 0" style="display: flex; flex-wrap: wrap; gap: 8px;">
                  <el-tag
                    v-for="file in responsesAttachement.attachments"
                    :key="file.id"
                    type="success"
                    effect="plain"
                    style="cursor: pointer;"
                    @click="downloadFilePage(file)"
                  >
                    <i :class="getFileIcon(file.name)" style="margin-right: 4px;"></i>
                    {{ file.name }}
                    <i class="el-icon-download" style="margin-left: 4px;"></i>
                  </el-tag>
                </div>
                <div v-else style="color: #909399;">暂无附件</div>
              </template>
              <template v-else>
                <UploadFile title="附件" :files="formData.Attachement" />
              </template>
            </el-form-item>
             
          </el-col>
        </el-row>
        
        <el-row style="margin-top: 16px;">
          <el-col :span="24" style="text-align: right;">
            <el-button
              v-if="!formData.IsSend"
              type="primary"
              :loading="submitting"
              @click="submitForm"
              icon="el-icon-check"
            >
              发起询标
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      </el-card>

    <!-- 询标成功提示对话框 -->
    <el-dialog
      :visible.sync="successDialog"
      title="询标成功"
      width="400px"
      center
    >
      <div style="text-align: center;">
        <i class="el-icon-success" style="color: #67c23a; font-size: 48px; margin-bottom: 16px;"></i>
        <div style="font-size: 16px; margin-bottom: 16px;">
          询标信息已成功提交，是否查看询标结果？
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">关闭页面</el-button>
        <el-button type="primary" @click="goToExpertHome">查看结果</el-button>
      </div>
    </el-dialog>
  </div> 
</template>

<script>
import UploadFile from "@/components/UploadFile.vue";
import { AddInquiryRecord,GetInquiryRecordById } from "@/api/InquiryRecord";
import { downloadFile as apiDownloadFile } from '../../api/api.js'
import router from "@/router";

export default {
  name: 'InquiryForm',
  components: {
    UploadFile
  },
  data() {
    return {
      // 简单状态
      loading: false,
      submitting: false,

      // 展示数据
      bidders: [],
      ProjectId: '',
      ProjectNo: '',
      Id: '',

      // 附件回显
      responsesAttachement: {
        attachments: []
      },

      // 表单数据
      formData: {
        ProjectId: '',
        InquiryUnits: [],
        Attachement: [],
        DeadlineTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        IsSend: false
      },

      // 对话框
      successDialog: false,

      // 表单验证规则
      rules: {
        DeadlineTime: [
          { required: true, message: '请选择询标截止时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    currentDate() {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    }
  },
  created() {
    // 从路由参数读取 Id，并回显
    const route = router.currentRoute
    this.Id = (route && route.query && route.query.Id) || ''
    if (this.Id) {
      this.fetchInquiryData()
    }
  },
  methods: {
    goToExpertHome() {
      router.push(`/expert/home?projectId=${this.ProjectId}&projectNo=${this.ProjectNo}`)
    },
    // 获取文件图标
    getFileIcon(fileName) {
      const ext = (fileName || '').split('.').pop().toLowerCase()
      switch (ext) {
        case 'pdf': return 'el-icon-document'
        case 'doc':
    case 'docx': return 'el-icon-document';
    case 'xls':
    case 'xlsx': return 'el-icon-s-grid';
    case 'jpg':
    case 'jpeg':
    case 'png': return 'el-icon-picture';
    default: return 'el-icon-document';
  }
},

// 文件下载方法
async downloadFilePage (file) {
  try {
    var params={
       path:file.FilePath,
       name:file.DisplayName  
    };
   await apiDownloadFile(params) 
  } catch (error) {
    console.error('下载文件失败:', error);
  } finally {
  }
},

async fetchInquiryData() {
  this.loading = true;
  try {
    const response = await GetInquiryRecordById(this.Id);
    if (response.IsSuccess && response.Data) {
      // 回显基本信息
      this.formData = {
        InquiryContent: response.Data.InquiryContent,
        // DeadlineTime: response.Data.DeadlineTime,
        IsSend: response.Data.IsSend,
        Attachement: response.Data.Attachement || [],
        ProjectId: response.Data.ProjectId,
        InquiryUnitsString: response.Data.InquiryUnitsString || '',
        ProjectNo: response.Data.ProjectNo,
        Id: response.Data.Id
      };
      // 回显项目信息
      this.ProjectNo = response.Data.ProjectNo;
      this.ProjectId = response.Data.ProjectId;
      
      // 回显投标单位
      if (response.Data.InquiryUnitsString != '') {
        this.bidders = this.parseInquiryUnits(response.Data.InquiryUnitsString);
      }
      
      // 回显附件列表
      if (response.Data.IsSend) {
        this.responsesAttachement.attachments = (response.Data.Attachement || []).map(file => ({
          id: file.Id,
          name: file.DisplayName,
          url: file.FileAllPath
        }));
      }
    }
  } catch (error) {
    console.error('获取询标记录失败:', error);
    alert('获取询标记录失败，请稍后重试');
  } finally {
    this.loading = false;
  }
},

// 转换方法
parseInquiryUnits(jsonString) {
  try {
    const cleanStr = (jsonString || '').replace(/\\\"/g, '"');
    const array = JSON.parse(cleanStr);
    if (!Array.isArray(array)) throw new Error('解析结果不是数组');
    return array.map(item => ({
      id: item.id || '',
      name: item.name || '',
      contactName: item.contactName || '',
      contactPhone: item.contactPhone || '',
      address: item.address || '',
      qualification: item.qualification || ''
    }));
  } catch (error) {
    console.error('解析投标单位数据失败:', error);
    return [];
  }
},

// 处理投标单位选择
handleBidderSelect(bidder) {
  this.selectedBidder = bidder;
  this.formData.bidderId = bidder.id;
  this.formData.bidderName = bidder.name;
  this.formData.contactPerson = bidder.contact;
  this.formData.contactPhone = bidder.phone;
},

// 搜索投标单位
searchBidders(query) {
  if (!query) return this.bidders;
  const searchText = (query || '').toLowerCase();
  return this.bidders.filter(bidder => 
    (bidder.name || '').toLowerCase().includes(searchText) ||
    (bidder.contact || '').toLowerCase().includes(searchText) ||
    (bidder.phone || '').includes(searchText)
  );
},

// 提交表单
async submitForm() {
  try {
    await this.$refs.form.validate();
  } catch (error) {
    this.$message.error('请填写完整信息');
    return;
  }

 

  if (!this.formData.DeadlineTime) {
    this.$message.error('请选择询标截止时间');
    return;
  }
  if (new Date(this.formData.DeadlineTime) <= new Date()) {
    this.$message.error('截止时间必须大于当前时间');
    return;
  }

  if (!this.formData.Attachement || this.formData.Attachement.length === 0) {
    this.$message.error('请上传询标附件');
    return;
  }

  this.formData.ProjectId = this.ProjectId;
  this.formData.IsSend = true; // 再次发起
  this.formData.InquiryUnitsString = JSON.stringify(this.bidders);

  this.submitting = true;
  try {
    await AddInquiryRecord(this.formData);
    this.successDialog = true;
    this.$message.success('询标发送成功');
  } catch (error) {
    console.error('提交失败:', error);
    this.$message.error('发送失败，请重试');
  } finally {
    this.submitting = false;
  }
},

// 关闭对话框并返回首页
closeDialog() {
  this.successDialog = false;
  router.push('/expert/home');
},

viewResult() {
  this.successDialog = false;
  router.push('/expert/home');
}
  }
};
</script>

<style scoped>
.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.welcome-card >>> .el-card__body {
  padding: 0;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.bidder-card {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.bidder-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.el-tag {
  margin: 2px;
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.el-form-item {
  margin-bottom: 18px;
}

.el-dialog {
  border-radius: 12px;
}

.dialog-footer {
  text-align: right;
}

.el-button {
  font-weight: 500;
}

/* 自定义卡片样式 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
</style>